import * as React from 'react';
import { saveAs } from 'file-saver'; // 假设你已经安装了 file-saver 包
import './download.css'
interface ImageDownloaderProps {
  defaultImageUrl?: string; // 默认图片URL
}

interface ImageDownloaderState {
  imageSrc: string | null;
  canvasDataUrl: string | null;
  format: string;
  showControls: boolean;
}

class ImageDownloaderWithButton extends React.Component<ImageDownloaderProps, ImageDownloaderState> {
  constructor(props: ImageDownloaderProps) {
    super(props);
    this.state = {
      imageSrc: props.defaultImageUrl || null,
      canvasDataUrl: null,
      format: 'jpeg',
      showControls: false,
    };
  }

  handleImageLoad = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        this.setState({
          imageSrc: e.target?.result as string,
          canvasDataUrl: null,
        }, () => this.generateImage());
      };
      reader.readAsDataURL(file);
    }
  };

  generateImage = () => {
    if (!this.state.imageSrc) return;

    const img = new Image();
    img.src = this.state.imageSrc;
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      if (ctx) {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0, img.width, img.height);
        const dataUrl = canvas.toDataURL(`image/${this.state.format}`, 1.0); // 1.0 是质量参数，对于JPEG有效
        this.setState({ canvasDataUrl: dataUrl });
      }
    };
  };

  handleFormatChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    this.setState({ format: event.target.value }, this.generateImage);
  };

  downloadImage = () => {
    const { format, canvasDataUrl } = this.state;

    if (!canvasDataUrl) return;

    saveAs(canvasDataUrl, `image.${format}`);
  };

  toggleControlsVisibility = () => {
    this.setState(prevState => ({ showControls: !prevState.showControls }));
  };

  render() {
    const { showControls } = this.state;

    return (
      <div className="controls-container">
        <button onClick={this.toggleControlsVisibility} className="controls-toggle">
          {showControls ? '下载' : '下载'}
        </button>
        {showControls && (
          <div className="controls">
            <input type="file" onChange={this.handleImageLoad} accept="image/*" />
            <select onChange={this.handleFormatChange}>
              <option value="jpeg">JPEG</option>
              <option value="png">PNG</option>
            </select>
            <button onClick={this.downloadImage}>无水印下载</button>
          </div>
        )}
      </div>
    );
  }
}

export default ImageDownloaderWithButton;